package com.security.handler;

import com.security.vo.OauthBaseVo;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * Created by 陈圣融 on 2017-07-31.
 */

public class Oauth2ParamsHandler {

    private String unoauthenticatedUrl = "/unoauthenticated";//未认证转发url
    private List<String> noCheckUrls = new ArrayList<>(Arrays.asList(unoauthenticatedUrl)); //无需匹配认证token url


    public void forwardUnoauth(HttpServletRequest request, HttpServletResponse response, OauthBaseVo oauthBaseErrorVo) throws ServletException, IOException {
        request.setAttribute("oauthBaseErrorVo", oauthBaseErrorVo);
        request.getRequestDispatcher(unoauthenticatedUrl).forward(request, response);
    }

    public boolean isNoCheckUrl(HttpServletRequest request) {
        PathMatcher pathMatcher = new AntPathMatcher();
        for (String noCkeckUrl : noCheckUrls) {
            if (pathMatcher.match(request.getContextPath() + noCkeckUrl, request.getRequestURI())) {
                return true;
            }
        }
        return false;
    }

    public String getUnoauthenticatedUrl() {
        return unoauthenticatedUrl;
    }

    public void setUnoauthenticatedUrl(String unoauthenticatedUrl) {
        this.noCheckUrls.remove(this.unoauthenticatedUrl);
        this.unoauthenticatedUrl = unoauthenticatedUrl;
        this.noCheckUrls.add(unoauthenticatedUrl);
    }

    public List<String> getNoCheckUrls() {
        return noCheckUrls;
    }

    public void setNoCheckUrls(List<String> noCheckUrls) {
        this.noCheckUrls = new ArrayList<>(noCheckUrls);
        this.noCheckUrls.add(unoauthenticatedUrl);
    }
}
